<?php
/**
 * Created by PhpStorm.
 * User: lingyun
 * Date: 2018/1/18
 * Time: 19:16
 * Desc: 门店推荐页面相关功能
 *      领取门店推荐页面优惠券 -- 领取更多页面优惠券
 */

namespace app\index\controller;

use think\Controller;

use think\Db;

use app\comm\controller\WebLogController;

class StoreIndex extends WebLogController{
    /**
     * @Author  lingyun
     * @Desc    门店关注券列表
     */
    public function store_coupon_list(){
        $store_id = session('store_id');

        $where = [
            'a.status'=>1,
            'a.is_deleted'=>0,
            'a.store_id'=>$store_id,
            'a.type'=>1
        ];

        $join = [
            ['ys_goods_category b','a.cat_id=b.id','LEFT'],
            ['ys_user_ycard c','a.id=c.coupon_id','LEFT']
        ];
        $coupon = db('store_coupon')->alias('a')->join($join)->where($where)->field('a.*,b.title,ifnull(c.coupon_id,0) as is_receive')->select();
        $this->assign('coupon',$coupon);
        return $this->fetch('store_coupon_list');
    }

    /**
     * @Author  lingyun
     * @Desc    领取门店关注优惠券
     */
    public function receive_store_coupon(){
        $uid = session('_user_uid_.uid');
        $id = input('id');      //门店关注券id
        $store_id = session('store_id');
        //优惠券详情
        $coupon = db('store_coupon')->where('id',$id)->find();

        //判断优惠券的类型 0商品优惠券，1关注券(不用判断发放数量以及领取时间) ， 2现金券
        if(!$coupon['type'] == 1){
            if($coupon['send_start_time']<time()){
                $this->error('暂未开放领取，请耐心等待','');
            }
            if($coupon['send_end_time']<time()){
                $this->error('领券时间已过，不能进行领取','');
            }
            if($coupon['create_num']<=$coupon['send_num']){
                $this->error('优惠券已被领完，不能进行领取','');
            }
        }
        //入库数据
        $data = [
            'store_id'=>$store_id,
            'uid'=>$uid,
            'coupon_id'=>$id,
            'order_id'=>0,
            'type'=>1,
            'cat_id'=>$coupon['cat_id'],
            'condition'=>$coupon['condition'],
            'morethan'=>$coupon['morethan'],
            'reduce'=>$coupon['reduce'],
            'use_start_time'=>$coupon['use_start_time'],
            'use_end_time'=>$coupon['use_end_time'],
            'price'=>$coupon['price'],
            'value'=>$coupon['value'],
            'is_used'=>0,
            'addtime'=>time()
        ];

        //入库操作
        $res = db('user_ycard')->data($data)->insert();
        if($res>0){
            if($coupon['type'] !=1 ){
                //增加领取数量
                db('store_coupon')->where('id',$coupon['id'])->setInc('send_num',1);
            }
            $this->success('领取成功','');
        }else{
            $this->error('领取失败','');
        }
    }

}
